/**
 *
 */
package com.starbaba.core.web.control;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.StrutsException;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.Result;
import com.opensymphony.xwork2.UnknownHandler;
import com.opensymphony.xwork2.XWorkException;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.entities.ActionConfig;
import com.opensymphony.xwork2.config.entities.PackageConfig;
import com.opensymphony.xwork2.config.entities.ResultConfig;
import com.opensymphony.xwork2.inject.Container;
import com.opensymphony.xwork2.inject.Inject;

/**
 * <p>
 * Title: CommonUnknownHandler
 * </p>
 *
 * <p>
 * Description: CommonUnknownHandler
 * </p>
 *
 * <p>
 * Copyright: Copyright (c) Revenco
 * </p>
 *
 * <p>
 * Company: Sunrise Tech Ltd.
 * </p>
 *
 * @author Lai Weilong
 *
 * @version 1.0
 *
 * @since 2011-10-1
 */
public class CommonUnknownHandler implements UnknownHandler {

    private static Map<String, ActionConfig> commonPathConfigs = new HashMap<String, ActionConfig>();

    protected Configuration configuration;
    protected ObjectFactory objectFactory;
    protected ServletContext servletContext;
    protected String parentPackageName; // 默认struts-package配置名
    protected PackageConfig commonPackage;

    protected final String DEFAULT_METHOD_NAME = "execute";
    protected final String DEFAULT_METHOD_RTN_SUCCESS = "success";
    protected final String DEFAULT_METHOD_RTN_ERROR = "error";
    protected final String JOIN_PACKAGE_AND_ACTION = ".view.";
    protected final String ACTION_SUFFIX = "Action";

    /**
	 *
	 */
    @Inject
    public CommonUnknownHandler(Configuration configuration, ObjectFactory objectFactory,
            ServletContext servletContext, Container container,
            @Inject("struts.unknownhandler.commonPackageName") String parentPackageName) {
        this.configuration = configuration;
        this.objectFactory = objectFactory;
        this.servletContext = servletContext;
        this.parentPackageName = parentPackageName;
        this.commonPackage = configuration.getPackageConfig(parentPackageName);
        if (commonPackage == null) {
            throw new ConfigurationException("Unknown default parent package [" + parentPackageName
                    + "]");
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.opensymphony.xwork2.UnknownHandler#handleUnknownAction(java.lang.
     * String, java.lang.String)
     */
    @Override
    public ActionConfig handleUnknownAction(String namespace, String actionName)
            throws XWorkException {

        // Strip the namespace if it is just a slash
        if (namespace == null || "/".equals(namespace)) {
            namespace = "";
        }

        if (StringUtils.isEmpty(actionName)) {
            return null;
        }

        String path = namespace + "/" + actionName;

        if (commonPathConfigs.containsKey(path)) {
            return commonPathConfigs.get(path);
        }

        Map<String, String> vars = null;

        Map<String, ActionConfig> actionConfigs = commonPackage.getActionConfigs();
        ActionConfig actionConfig = actionConfigs.get(actionName);

        if (actionConfig != null) {
            vars = this.getCommonVars(path);
        } else {
            actionConfig = actionConfigs.get("index");
            vars = this.getCommonVars(path + "/index");
        }

        if (vars == null) {
            return null;
        }

        if (null != actionConfig) {
            actionConfig = convertActionConfig(actionConfig, vars);
            commonPathConfigs.put(path, actionConfig);
            return actionConfig;
        } else {
            throw new StrutsException("Unable to find a location for [" + path + "]");
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.opensymphony.xwork2.UnknownHandler#handleUnknownActionMethod(java
     * .lang.Object, java.lang.String)
     */
    @Override
    public Object handleUnknownActionMethod(Object action, String methodName)
            throws NoSuchMethodException {
        // TODO Auto-generated method stub
        return null;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.opensymphony.xwork2.UnknownHandler#handleUnknownResult(com.opensymphony
     * .xwork2.ActionContext, java.lang.String,
     * com.opensymphony.xwork2.config.entities.ActionConfig, java.lang.String)
     */
    @Override
    public Result handleUnknownResult(ActionContext actionContext, String actionName,
            ActionConfig actionConfig, String resultCode) throws XWorkException {
        // TODO Auto-generated method stub
        return null;
    }

    protected ActionConfig convertActionConfig(ActionConfig orig, Map<String, String> vars) {
        ActionConfig.Builder builder = new ActionConfig.Builder(orig);
        builder.className(convertParam(orig.getClassName(), vars));

        for (String resultName : orig.getResults().keySet()) {
            ResultConfig resultConfig = orig.getResults().get(resultName);

            ResultConfig.Builder rcBuilder = new ResultConfig.Builder(resultConfig.getName(),
                    resultConfig.getClassName());

            rcBuilder.className(convertParam(resultConfig.getClassName(), vars));

            String location = resultConfig.getParams().get("location");

            String newLoc = convertParam(location, vars);

            rcBuilder.addParam("location", newLoc);

            rcBuilder.location(orig.getLocation());

            builder.addResultConfig(rcBuilder.build());
        }

        return builder.build();
    }

    /**
     * Seperate the giving namespace to common pattern vars.
     *
     * @param namespace
     * @return
     */
    protected Map<String, String> getCommonVars(String namespace) {

        if (namespace == null || namespace.length() == 0) {
            return null;
        }

        String[] items = namespace.split("/");

        int length = items.length;

        if (length < 3) {
            return null;
        } else {
            String keyword = items[length - 1];

            String entity = items[length - 2];

            StringBuffer moduleSlash = new StringBuffer();
            for (int i = 0; i < length - 2; i++) {
                if (items[i] != null && items[i].trim().length() > 0) {
                    moduleSlash.append(items[i]);
                    if (i < length - 3) {
                        moduleSlash.append("/");
                    }
                }
            }

            Map<String, String> vars = new HashMap<String, String>();

            vars.put("keyword", keyword);
            vars.put("entity", entity);
            vars.put("moduleSlash", moduleSlash.toString());
            vars.put("moduleDot", moduleSlash.toString().replaceAll("/", "."));
            vars.put("entityCapFirst", StringUtils.capitalize(entity));

            return vars;
        }
    }

    /**
     * Inserts into a value pre-define-pattern-matched strings where specified.
     *
     * @param val
     *            The value to convert
     * @param vars
     *            A Map of wildcard-matched strings
     * @return The new value
     */
    @SuppressWarnings("rawtypes")
    protected String convertParam(String val, Map<String, String> vars) {
        if (val == null) {
            return null;
        } else if (val.indexOf("{") == -1) {
            return val;
        }

        StringBuffer key = null;
        for (Iterator i = vars.keySet().iterator(); i.hasNext();) {
            String varKey = (String) i.next();

            key = new StringBuffer("\\{").append(varKey).append("\\}");

            // Replace all instances of the placeholder
            val = val.replaceAll(key.toString(), vars.get(varKey));
        }
        return val;
    }

}
